package com.app.GoCuro.util;

import java.util.UUID;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/*
 * Accessor for a unique device Id stored in shared preferences.
 * 
 * If the Id is not in the shared preferences, one is generated 
 * and written out. Note, this UUID does not persist across phone
 * wipes but should persist across app reinstallation.
 * 
 *  Code is heavily based off of Reto Meier's talk at Google I/O 2011.
 *  http://www.google.com/events/io/2011/sessions/android-protips-advanced-topics-for-expert-android-app-developers.html
 */
public class DeviceIdGenerator 
{
	private static String uniqueID;
	private static final String UNIQUE_ID_PREF = "UNIQUE_ID";
	
	/*
	 * Returns the unique ID from the preferences file, creating one if it does not exist'
	 * 
	 * @param Context context		the calling context, usually passed in activity
	 * @return 						the unique ID string
	 */
	public synchronized static String getId(Context context)
	{
		//retrieve the unique Id if not already assigned
		if (uniqueID == null)
		{
			SharedPreferences sharedPreferences = context.getSharedPreferences(UNIQUE_ID_PREF, Context.MODE_PRIVATE);
			uniqueID = sharedPreferences.getString(UNIQUE_ID_PREF, null);
			
			//id was not in the shared preferences so generate a new one and commit it
			if (uniqueID == null)
			{
				uniqueID = UUID.randomUUID().toString();
				Editor editor = sharedPreferences.edit();
				editor.putString(UNIQUE_ID_PREF, uniqueID);
				editor.commit();
			}
		}
		
		return uniqueID;
	}
	
	
	

}
